package com.bicon.life.core.base.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 * @author miou
 * Created by FengYxin on 2016/9/29.
 */
public class EncryptionUtil {

    /*
   * 方法名称：getMD5
   * 功    能：字符串MD5加密
   * 参    数：待转换字符串
   * 返 回 值：加密之后字符串
   */
    public static String getMD5(String sourceStr) throws UnsupportedEncodingException {
        String resultStr = "";
        try {
            byte[] temp = sourceStr.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(temp);
            // resultStr = new String(md5.digest());
            byte[] b = md5.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                        '9', 'A', 'B', 'C', 'D', 'E', 'F' };
                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4) & 0X0F];
                ob[1] = digit[b[i] & 0X0F];
                resultStr += new String(ob);
            }
            return resultStr;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getMD5Str(String str) {
        MessageDigest md = null;
        StringBuffer sbuffer = new StringBuffer();
        try {
            md = MessageDigest.getInstance("MD5");
            StringBuilder sb = new StringBuilder(str);
            md.update(sb.toString().getBytes());

            byte[] bs = md.digest();
            for (byte b : bs) {
                int v = b & 0xFF;
                if (v < 16) {
                    sbuffer.append(0);
                }
                sbuffer.append(Integer.toHexString(v));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // System.err.println("getmd5: " + sbuffer);
        return sbuffer.toString();
    }
}
